import * as npm from "npm";
import * as url from "url";
import axios from "axios";
import * as util from "util";
import { CfgStorage } from "../cfg";

export const load = util.promisify<any, any>(npm.load);

export const bootstrap = async (): Promise<any> => {
  const registry = CfgStorage.getInstance().get("cnpm.registry");
  await load({
    registry,
    scope: "@qianmi",
    progress: false,
    loglevel: "silent"
  });
  return {
    init: util.promisify(npm.commands.init),
    install: util.promisify(npm.commands.install),
    view: util.promisify<any, string[], boolean>(npm.commands.view as any),
    publish: util.promisify(npm.commands.publish)
  };
};

export const isPkgNameOK = (pkgName: string) => {
  const ret: number[] = [];
  pkgName.split("").forEach((c, i) => {
    if (!/[0-9a-z\-]/.test(c)) {
      ret.push(i);
    }
  });
  return ret;
};

export const isPkgExist = async (pkgName: string, registry?: string) => {
  if (registry === undefined) {
    registry = CfgStorage.getInstance().get("cnpm.registry") as string;
  }
  const u = url.resolve(registry, encodeURIComponent(pkgName).replace(/^%40/, "@"));
  const headers = {
    accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*",
    responseType: "text"
  };
  try {
    const resp = await axios.get(u, {
      headers,
      timeout: 30000
    });
    return resp.status === 200;
  } catch (e) {
    if (e.response.status === 404) return false;
    throw e;
  }
};
